package com.example.geolocalizacion;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.w3c.dom.Document;

import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class MainActivity extends FragmentActivity {
	private static final String TAG = "Geolocalizacion";
	private GoogleMap map;
	LocationManager locationManager;
	Location startPosition = null;
	Location lastPosition = null;

	Button startFinishButton;

	double speed = 0;
	double distance = 0;

	// TextViews de la pantalla
	TextView counterTextView;
	TextView speedTextView;
	TextView distanceTextView;

	// Datos para el tiempo dinamico
	double time = 0;
	DecimalFormat df = new DecimalFormat("#0.00");
	Timer counterTimer = new Timer();
	GMapV2Direction mapDirection = new GMapV2Direction();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// Si el servicio de Google Play está funcionando
		if (GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getApplicationContext()) == ConnectionResult.SUCCESS) {
			// Crea el Location Manager para que pueda manejar con el cambio de
			// localizaciones
			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			LocationListener locationListener = new MyLocationListener();
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
			map = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
		}

		counterTextView = (TextView) findViewById(R.id.counter);
		speedTextView = (TextView) findViewById(R.id.speed);
		startFinishButton = (Button) findViewById(R.id.start);
		distanceTextView = (TextView) findViewById(R.id.distance);
	}

	public void start(View v) {
		// Si el boton es para iniciar
		Log.i(TAG, "PASA QUI");
		if (startFinishButton.getText().toString().equals("Iniciar")) {
			// Crea la task del Contador
			TimerTask timerCounterTask = new TimerTask() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							counterTextView.setText(df.format(time));
							time += 0.1;
						}
					});
				}
			};
			counterTimer.schedule(timerCounterTask, 0, 100);
			startFinishButton.setText("Finalizar");

		} else {
			counterTimer.cancel();
		}
	}

	public double getSpeed(double distance, double time) {
		return Double.parseDouble(df.format(distance * 3.6 / time));
	}

	private class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location loc) {
			if (!startFinishButton.getText().toString().equals("Iniciar")) {
				if (startPosition == null) {
					startPosition = loc;
					lastPosition = loc;
					map.clear();
					map.addMarker(new MarkerOptions().position(
							new LatLng(loc.getLatitude(), loc.getLongitude()))
							.title("Posicion Inicial"));
					// Mueve la camara para el marker
					map.moveCamera(CameraUpdateFactory.newLatLngZoom(
							new LatLng(loc.getLatitude(), loc.getLongitude()),
							15));
					map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000,
							null);
				} else {
					distance += loc.distanceTo(lastPosition);
					distanceTextView.setText("" + (distance / 1000));
					drawRoute(new LatLng(lastPosition.getLatitude(),
							lastPosition.getLongitude()),
							new LatLng(loc.getLatitude(), loc.getLongitude()));
					lastPosition = loc;
					speedTextView.setText("" + getSpeed(distance, time));
				}
			}
		}

		// Método para pintar el mapa con la ruta
		public void drawRoute(LatLng sourcePosition, LatLng destPosition) {
			Document doc = mapDirection.getDocument(sourcePosition,
					destPosition, GMapV2Direction.MODE_DRIVING);

			ArrayList<LatLng> directionPoint = mapDirection.getDirection(doc);
			PolylineOptions rectLine = new PolylineOptions().width(3).color(
					Color.RED);
			for (int i = 0; i < directionPoint.size(); i++) {
				rectLine.add(directionPoint.get(i));
			}
			Polyline polylin = map.addPolyline(rectLine);
		}

		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Disabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Gps Enabled",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

}